﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using CustomControls.InheritedFrameworkControls;
using MallInteractiveMap.ClientDataHandler;
using MallInteractiveMap.Common;
using MallInteractiveMap.DTO;
using MallInteractiveMap.Language;

namespace MallInteractiveMap
{
    public class DatabaseSetup
    {
        private int _categoryId;
        private void SaveFloor()
        {
            string error = null;
            List<DTOMall> malls = ClientData.GetMall(new Common.QueryParamList(), ref error);
            List<DTOCategory> categories = ClientData.GetCategory(new QueryParamList(), ref error);

            if (malls.Count <= 0 || categories.Count <=0) return;
            _categoryId = categories[0].Id;
            DTOFloor floor = new DTOFloor
            {
                Name = "Ground floor",
                FloorIndex = 1,
                MallId = malls[0].Id,
                IsNew = true,
                MapId = 1,
                Description = "None",
                LastUpdated = DateTime.Now
            };
            SaveFloor(floor);
             floor = new DTOFloor
            {
                Name = "First floor",
                FloorIndex = 2,
                MallId = malls[0].Id,
                IsNew = true,
                MapId = 2,
                Description = "None",
                LastUpdated = DateTime.Now
            };
            SaveFloor(floor);
            floor = new DTOFloor
            {
                Name = "Second floor",
                FloorIndex = 3,
                MallId = malls[0].Id,
                IsNew = true,
                MapId = 2,
                Description = "None",
                LastUpdated = DateTime.Now
            };
            SaveFloor(floor);

        }
        private void SaveFloor(DTOFloor floor)
        {
            if (SetData(floor))
            {
                floor.Id = ClientData.GetFloorId();
                if (floor.Id <= 0) return;
                var lobbyMap = new MapPresenter().GetMap(floor.FloorIndex);
                foreach (var mapElement in lobbyMap.MapElements)
                {
                    var element = (MapElement)mapElement;
                    element.Id = element.Viewbox.Tag.ToString();

                    //if (ConfigurationManager.AppSettings["SaveDemoShops"].Equals("true"))
                    SaveShops(element.Id, floor.Id);

                }
            }

        }
        private void SaveShops(string shopNo, int floorId)
        {
            var shop = new DTOShop { ShopNo = shopNo, FloorId = floorId, CategoryId = _categoryId, IsNew = true };
            shop.Title = string.Format(LanguageLoader.GetText("Shop_{0}"), shop.ShopNo);
            shop.Email = "xyz@gmail.com";
            shop.LastUpdated = DateTime.Now;
            var error = string.Empty;
            var currentDirectory = Directory.GetCurrentDirectory();
            var pics = Directory.GetFiles(currentDirectory + "\\DemoShopImages");
            var photos = new List<DTOShopPhotos>();
            foreach (string pic in pics)
            {
                var photo = new DTOShopPhotos();
                var fileStream = File.Open(pic, FileMode.Open, FileAccess.Read);
                var imagData = new byte[fileStream.Length];
                fileStream.Read(imagData, 0, (int)fileStream.Length);
                photo.ShopImage = imagData;
                fileStream.Close();
                var file = new FileInfo(pic);
                photo.FileName = file.Name;
                photo.FileType = "image/jpeg";
                photo.IsNew = true;
                photo.LastUpdated = DateTime.Now;
                photo.Description = LanguageLoader.GetText("None");
                photos.Add(photo);
            }
            shop.Photos = photos;
            ClientData.SaveShop(shop, ref error);
            if (!string.IsNullOrEmpty(error))
            {

            }
        }
        private bool SetData(DTOFloor oFloor)
        {
            QueryParamList param = new QueryParamList();
            if (!oFloor.IsNew)
            {
                param.Add(new QueryParamObj() { ParamName = "Id", DBType = DbType.Int32, ParamValue = oFloor.Id });
            }
            else
            {
                param.Add(new QueryParamObj() { ParamName = "LanguageType", DBType = DbType.Int32, ParamValue = LanguageLoader.CurrentLanguageType });
            }
            param.Add(new QueryParamObj() { ParamName = "MallId", DBType = DbType.Int32, ParamValue = oFloor.MallId });
            param.Add(new QueryParamObj() { ParamName = "MapId", DBType = DbType.Int32, ParamValue = oFloor.MapId });
            param.Add(new QueryParamObj() { ParamName = "Name", DBType = DbType.String, ParamValue = oFloor.Name });
            param.Add(new QueryParamObj() { ParamName = "FloorIndex", DBType = DbType.Int32, ParamValue = oFloor.FloorIndex });
            param.Add(new QueryParamObj() { ParamName = "Description", DBType = DbType.String, ParamValue = oFloor.Description });
            param.Add(new QueryParamObj() { ParamName = "LastUpdated", DBType = DbType.DateTime, ParamValue = oFloor.LastUpdated });
            string error = string.Empty;
            string spName = oFloor.IsNew ? "INSERTFloor " : "UPDATEFloor";
            bool isSuccess = ClientData.SetData(param, spName, ref error);
            return string.IsNullOrEmpty(error) & isSuccess;
        }
        private void DeleteShopFloor()
        {
            var error = string.Empty;
            ClientData.ExecuteQuery("DELETE FROM ShopPhotos;DELETE FROM Shop;DELETE FROM Floor;", null, ref error);
        }
        public void InitializeDatabase()
        {
            DeleteShopFloor();
            SaveFloor();
            UpdateConfiguration();
        }

        private void UpdateConfiguration()
        {
            // Open App.Config of executable

            System.Configuration.Configuration config =
             ConfigurationManager.OpenExeConfiguration
                        (ConfigurationUserLevel.None);

            // Add an Application Setting.

            config.AppSettings.Settings["SetupDatabase"].Value = "false";

            // Save the changes in App.config file.

            config.Save(ConfigurationSaveMode.Modified);

            // Force a reload of a changed section.

            ConfigurationManager.RefreshSection("appSettings");

        }
    }
}
